from django.shortcuts import render
from django.http import HttpResponse
from tb_info.models import *
from django.db.models import Q
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
# from inform.aaa import PostHandler
import requests
import datetime
import json
from tb_info.function.user_list import get_full_org2, downtree, get_org_people, get_full_org3
from rest_framework import status as status_code
import threading
import queue
import requests
import os
from rest_framework.decorators import api_view
from rest_framework.response import Response
from wfs.function.produce_pdf import approvel, by_approval, delete_pdf, by_pdf, by_form_pdf, form_pdf, approvel2, \
    by_approval2


# Create your views here.


def response_origin(data):
    response = Response(data)
    response['Access-Control-Allow-Origin'] = '*'
    return response


def toJson(func):
    def wrapper(*args, **kwargs):
        dicts = func(*args, **kwargs)
        response = HttpResponse()
        response['Access-Control-Allow-Origin'] = '*'
        response["Access-Control-Allow-Credentials"] = "true"
        response['Content-Type'] = 'application/json'
        response.write(json.dumps(dicts))
        return response

    return wrapper


# @api_view(http_method_names=["GET"])
# def test_aaa(request):
#     if request.method =="GET":
#         list1 = get_org_people(52)
#         # print(list1)
#         return response_origin({"data":list1})


def save_lists(uname):
    try:
        # uname = request.GET["uname"]
        userID = TbUser.objects.filter(username=uname).values("id")[0]["id"]
        org_id1 = TbUserOrg.objects.filter(user_id=userID)
        # print(org_id1)
        if not org_id1.exists():
            return "No data"
        elif org_id1.count() > 1:
            list1 = []
            lit1 = []
            lit2 = []
            lit3 = []
            for iii in org_id1:
                org_id2 = iii.org_id
                orgID, org_level = get_full_org2(org_id2)
                lit1.append(orgID)
            org_list1, org_list2 = downtree(lit1, lit2, lit3)
            org_list3 = list(set(org_list2).union(set(org_list1)))
            org_list = list(set(org_list3).union(set(lit1)))
            for org_id3 in org_list:
                dict1 = TbUserOrg.objects.filter(org_id=org_id3).exclude(user_id=userID)
                for i in dict1:
                    userId = i.user_id
                    user_head = i.user.head and settings.MEDIA_ROOT + i.user.head or i.user.head
                    dict2 = {"username": i.user.username, "email": i.user.email, "is_active": i.user.is_active,
                             "first_name": i.user.first_name, "last_name": i.user.last_name, "head": user_head,
                             "ext": i.user.ext, "mobile_phone": i.user.mobile_phone, "user_id": userId,
                             "org": i.org.org_name}
                    list1.append(dict2)
            return list1
        else:
            org_id2 = org_id1.values("org_id")[0]["org_id"]
            orgID, org_level = get_full_org2(org_id2)
            list1 = []
            lit1 = []
            lit2 = []
            lit3 = []
            lit1.append(orgID)
            org_list1, org_list2 = downtree(lit1, lit2, lit3)
            org_list = list(set(org_list2).union(set(org_list1)))
            org_list.append(orgID)
            for org_id3 in org_list:
                dict1 = TbUserOrg.objects.filter(org_id=org_id3).exclude(user_id=userID)
                for i in dict1:
                    userId = i.user_id
                    user_head = i.user.head and settings.MEDIA_ROOT + i.user.head or i.user.head
                    dict2 = {"username": i.user.username, "email": i.user.email, "is_active": i.user.is_active,
                             "first_name": i.user.first_name, "last_name": i.user.last_name, "head": user_head,
                             "ext": i.user.ext, "mobile_phone": i.user.mobile_phone, "user_id": userId,
                             "org": i.org.org_name}
                    list1.append(dict2)

            return list1
            # return response_origin({"status":status_code.HTTP_200_OK,"data":list1})
    except Exception as e:
        # print(e)
        return "No data"


@api_view(http_method_names=["GET"])
def user_list(request):
    try:
        uname = request.user.username
        # print(request.user.id,request.user.username)
        v = UserList.objects.filter(user__username=uname)
        if v.exists():
            userID = v.values("user_id")[0]["user_id"]
            to = v.values("timeout")[0]["timeout"]
            if int(to) == 0:
                for i in v:
                    b = i.user_list
                    if b == "False":
                        UserList.objects.filter(user_id=userID).update(user_list="No data", timeout=1)
                        return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "data": "Please try again !"})
                    userList = eval(b)
                    # list1 = [eval(i.user_list) for i in v]
                    return response_origin({"status": status_code.HTTP_200_OK, "data": userList})
            else:
                list1 = save_lists(uname)
                if list1 == "No data":
                    UserList.objects.filter(user_id=userID).update(user_list=list1, timeout=1)
                    return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "data": list1})
                else:
                    UserList.objects.filter(user_id=userID).update(user_list=list1, timeout=0)
                    return response_origin({"status": status_code.HTTP_200_OK, "data": list1})
        else:
            userID = TbUser.objects.filter(username=uname).values("id")[0]["id"]
            list1 = save_lists(uname)
            if list1 == "No data":
                uList = UserList()
                uList.user_id = userID
                uList.user_list = list1
                uList.timeout = 1
                uList.save()
                return response_origin({"status": status_code.HTTP_200_OK, "data": list1})
            uList = UserList()
            uList.user_id = userID
            uList.user_list = list1
            uList.timeout = 0
            uList.save()
            return response_origin({"status": status_code.HTTP_200_OK, "data": list1})

    except Exception as e:
        return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "message": str(e)})


@api_view(http_method_names=["GET", 'POST', 'PUT', 'DELETE'])
def group_info(request):
    if request.method == "POST":
        try:
            result = request.data
            employee_name = request.user.username
            members = result['members'].replace("null","None")
            group_name = result['group_name']
            cgroup = GroupInfo()
            cgroup.employee_name = employee_name
            cgroup.member = members
            cgroup.group_name = group_name
            cgroup.save()
            return response_origin({"status": status_code.HTTP_201_CREATED})
        except Exception as e:
            error = str(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": error})
    elif request.method == "DELETE":
        try:
            result = request.data
            groupId = result['group_id']
            GroupInfo.objects.filter(id=groupId).delete()
        except Exception as e:
            error = str(e)
            return response_origin({"status": status_code.HTTP_400_BAD_REQUEST, "message": error})
        return response_origin({"status": status_code.HTTP_200_OK})
    elif request.method == "PUT":
        try:
            result = request.data
            group_id = result['groupId']
            employee_name = request.user.username
            groupName = result['groupName']
            group_member = result['groupMember'].replace("null","None")
            # if GroupInfo.objects.filter(group_name=groupName,employee_name=employee_name):
            #     return {"status":"False", "message":"No repeat group name"}

            GroupInfo.objects.filter(id=group_id, employee_name=employee_name).update(group_name=groupName,
                                                                                      member=group_member)
        except Exception as e:
            error = str(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": error})
        return response_origin({"status": status_code.HTTP_202_ACCEPTED})


@api_view(http_method_names=["GET"])
def group2(request, userID):
    if request.method == "GET":
        try:
            employee_name = TbUser.objects.filter(id=userID).values("username")[0]['username']
            group_info = GroupInfo.objects.filter(employee_name=employee_name)
            list_data = []
            for gData in group_info:
                b = gData.member
                b = eval(b.replace("null", "None"))
                dicts = {"group_name": gData.group_name, "group_member": b, "group_id": gData.id,
                         "employee_name": gData.employee_name}
                list_data.append(dicts)
            return response_origin({"status": status_code.HTTP_200_OK, "data": list_data})
        except Exception as e:
            return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "message": str(e)})


@api_view(http_method_names=["GET", 'POST', 'DELETE'])
def sub_info(request):
    if request.method == "POST":
        try:
            result = request.data
            prod = result["product"]
            line = result['line']
            station = result['station']
            uname = result['username']
            m = prod.split(",")
            n = line.split(",")
            o = station.split(",")
            for i in range(0, len(m)):
                obj, created = SubscriptionInfo.objects.get_or_create(product=m[i], line=n[i], station=o[i],
                                                                      username=uname)
                # print(obj)
                # print(created)
            return response_origin({"status": status_code.HTTP_201_CREATED})
        except Exception as e:
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": str(e)})
    elif request.method == "GET":
        try:
            result = request.data
            username = result['username']
            subData = SubscriptionInfo.objects.filter(username=username)
            lists = []
            for sub_list in subData:
                dicts = {"product": sub_list.product, "line": sub_list.line, "station": sub_list.station,
                         "username": sub_list.username}
                lists.append(dicts)
            return response_origin({"status": status_code.HTTP_200_OK, "data": lists})
        except Exception as e:
            return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "message": str(e)})
    elif request.method == "DELETE":
        try:
            result = request.data
            line = result['line']
            uname = result["username"]
            SubscriptionInfo.objects.filter(line=line, username=uname).delete()
            return response_origin({"status": status_code.HTTP_200_OK})
        except Exception as e:
            return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "message": str(e)})


@api_view(http_method_names=["GET", 'POST'])
def meeting_info(request):
    if request.method == "POST":
        try:
            result = request.data
            title = result['title']
            meeting_time = result['meeting_time']
            meeting_room = result['meeting_room']
            joiner = result['joiner']
            content = result['content']
            username = result['sender']
            send_time = result['send_time']
            isRead = result['isRead']
            exs = MeetingInfo.objects.filter(sendTime=send_time, username=username).exists()
            if exs:
                return {"status": "False", "message": "Message already exists"}
            s = MeetingInfo()
            s.title = title
            s.inform_time = meeting_time
            s.meetingRoom = meeting_room
            s.attendant = joiner
            s.content = content
            s.username = username
            s.sendTime = send_time
            s.status = isRead
            s.save()
        except Exception as e:
            errors = str(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": errors})
        return response_origin({"status": status_code.HTTP_201_CREATED})
    elif request.method == "GET":
        try:
            result = request.data
            employee_id = result['employee_name']
            search = MeetingInfo.objects.filter(
                Q(attendant__icontains=employee_id) | Q(username__icontains=employee_id))
            lists = []
            for i in search:
                dicts = {"title": i.title, "meeting_room": i.meetingRoom, "joiner": i.attendant,
                         "meeting_time": i.inform_time, "sendTime": i.sendTime, "sender": i.username,
                         "content": i.content, "isRead": i.status}
                lists.append(dicts)
            return {"status": status_code.HTTP_200_OK, "data": lists}
        except Exception as e:
            return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "message": str(e)})


@api_view(http_method_names=["GET", 'POST'])
def exc_info(request):
    if request.method == "POST":
        try:
            result = request.data
            prod = result["product"]
            line = result['line']
            station = result['station']
            description = result['description']
            joiner = result['joiner']
            username = result['employee_name']
            send_time = result['send_time']
            exc_time = result["exc_time"]
            isRead = result['isRead']
            img = result['img']

            exs = ExceptionInfo.objects.filter(sendTime=send_time, username=username).exists()
            if exs:
                return {"status": "False", "message": "Message already exists"}
            exInform = ExceptionInfo()
            exInform.product = prod
            exInform.line = line
            exInform.station = station
            exInform.description = description
            exInform.attendant = joiner
            exInform.username = username
            exInform.sendTime = send_time
            exInform.status = isRead
            exInform.exception_time = exc_time
            exInform.img = img
            exInform.save()
        except Exception as e:
            errors = str(e)
            return {"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": errors}
        return {"status": status_code.HTTP_201_CREATED}
    elif request.method == "GET":
        try:
            result = request.data
            employee_id = result['employee_name']
            search = ExceptionInfo.objects.filter(
                Q(attendant__icontains=employee_id) | Q(username__icontains=employee_id))
            lists = []
            for i in search:
                dicts = {"product": i.product, "line": i.line, "joiner": i.attendant, "station": i.station,
                         "description": i.description, "status": i.status, "employee_name": i.username,
                         "send_time": i.sendTime,
                         "exc_time": i.exception_time, "exc_img": i.img}
                lists.append(dicts)
            return response_origin({"status": status_code.HTTP_200_OK, "data": lists})
        except Exception as e:
            return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "message": str(e)})


@api_view(http_method_names=["PUT"])
def read(request):
    if request.method == "PUT":
        try:
            result = request.data
            sender = result["sender"]
            send_time = result["send_time"]
            isRead = result["isRead"]
            read_type = result["type"]
            if read_type == "meeting":
                MeetingInfo.objects.filter(username=sender, sendTime=send_time).update(status=isRead)
                return response_origin({"status": status_code.HTTP_202_ACCEPTED})
            elif read_type == "exception":
                ExceptionInfo.objects.filter(username=sender, sendTime=send_time).update(status=isRead)
                return response_origin({"status": status_code.HTTP_202_ACCEPTED})
            else:
                return response_origin(
                    {"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": "that is not correct type"})
        except Exception as e:
            return response_origin({"status": status_code.HTTP_400_BAD_REQUEST, "message": str(e)})


def download(request):
    file = '1.json'
    content = open(os.path.join("var", "www", "cpe", "download", file), 'rb').read()
    return HttpResponse(content)


# @toJson
# def conn(request):
#     from http.server import HTTPServer
#
#     sever = HTTPServer(('10.132.37.36', 9092), PostHandler)
#     print('Starting server, use <Ctrl-C> to stop')
#     sever.serve_forever()
#     return {"status":"OK"}


@api_view(http_method_names=["POST"])
def sendMsn(request):
    aa = ''


@api_view(http_method_names=["GET"])
def add_org_people(request):
    # downtree()
    from django.conf import settings
    from tb_forms.functions.db import DB
    sql = "select id from tb_org where is_active = 1 order by org_level_id LIMIT 1;"
    dblist = settings.DATABASES['default']
    con = DB(user=dblist['USER'], password=dblist['PASSWORD'], host=dblist['HOST'], port=int(dblist['PORT']),
             sid=dblist['NAME'], dbname='mysql')
    con.get_cur()
    org_a = con.queryone(sql)
    data = get_org_people(org_a[0])
    for i in data:
        TbOrg.objects.filter(id=i['org_id']).update(org_people=i["num"])
    orgID = [org.id for org in TbOrg.objects.all()]
    for id2 in orgID:
        # print(id2)
        list1 = [id2]
        list2 = []
        list3 = []
        list4 = []
        r1, r2 = downtree(list1, list2, list3)
        # print(type(r1))
        r1 = r1 + list1
        # print(r1,r2)
        org_list3 = list(set(r1).union(set(r2)))
        # print(org_list3)
        # d = get_full_org3(48)
        # print(org_list3)
        for i in org_list3:
            num = TbUserOrg.objects.filter(org_id=i).count()
            list4.append(num)
        all_num = sum(list4)
        TbOrg.objects.filter(id=id2).update(org_people_all=all_num)
        # print(all_num)

    return response_origin({"status": "True"})


from wfs import models


@api_view(http_method_names=["GET"])
def pdf_ana(request):
    name = [{"username": "F1331855", "msn": "主管簽核"}, {"username": "F1330319", "msn": "人資簽核"},
            {"username": "F1330314", "msn": "主管簽核"}, {"username": "F1328483", "msn": "主管簽核"},
            # ]
            {"username": "F1332580", "msn": "主管簽核"}, {"username": "F1331349", "msn": "人資審核"},
            {"username": "F1307494", "msn": "主管簽核"}, {"username": "F1605151", "msn": "隨便定義"},
            # {"username":"F8977114","msn":"數據定時"},
            # {"username":"F1661587","msn":"手機卡我"},{"username":"F1661587","msn":"手機卡我"}

            ]
    img_path1 = 'D:/photos/files/ST/workflow/file'
    img_path2 = 'E:/delpdf/F1331855.png'
    sign_all = [{"sign_img": img_path2, "username": "F1331sd", "sign_title": "主管簽核",
                 "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711), "sign_color": "red"},
                {"sign_img": img_path2, "username": "F1331a", "sign_title": "2b",
                 "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711), "sign_color": "black"},
                {"sign_img": img_path2, "username": "F1331S", "sign_title": "2b",
                 "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711), "sign_color": "black"},
                {"sign_img": img_path2, "username": "F1331S2", "sign_title": "2b",
                 "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711), "sign_color": "black"},
                {"sign_img": img_path2, "username": "F133SA5", "sign_title": "2b",
                 "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711), "sign_color": "black"},
                #
                # {"sign_img": img_path2, "username": "F1331SAD5", "sign_title": "2b",
                #  "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711),"sign_color":"black"},
                # {"sign_img": img_path2 , "username": "F133SDA5", "sign_title": "2b",
                #  "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711)},
                # {"sign_img": img_path2 , "username": "F133A55", "sign_title": "2b",
                #  "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711)},
                # {"sign_img": img_path2 , "username": "F133AS55", "sign_title": "2b",
                #  "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711)},
                # {"sign_img": img_path2, "username": "F1331R5", "sign_title": "2b",
                #  "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711)},
                # {"sign_img": img_path2, "username": "F1331RE55", "sign_title": "2b",
                #  "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711)},
                # {"sign_img": img_path2, "username": "F133W5", "sign_title": "2b",
                #  "sign_time": datetime.datetime(2017, 7, 27, 17, 57, 21, 539711)},
                ]
    # path = 'D:/photos/files/ST/workflow/file/qw.pdf'

    # record_id = request.GET['record_id']

    # pdf_path = '/mysite/files/ST/pdf'+"/444.pdf"
    # pdf_path = 'D:/456.pdf'
    pdf_path = 'E:/delpdf/ok.pdf'
    d, list1 = by_approval2(sign_all, pdf_path, time_staff='adf', people=8, sign_people=5,
                            ser_img="E:/delpdf/test3.jpg",
                            ser_num="ETS0011708140002")
    # d,lis1 = approvel2(name,pdf_path,ser_num='SMS0011708160018',ser_img='E:/delpdf/vo.jpg')
    # d = form_pdf(record_id,pdf_path)
    # d,lists = by_pdf(record_id,d)
    # delete_pdf(lists,pdf_path)
    # by_form_pdf(record_id,pdf_path)
    return response_origin({"status": "True"})


@api_view(http_method_names=["GET"])
def by_app(request):
    if request.method == "GET":
        id = request.GET['record_id']
        by_pdf(id)
        return response_origin({"status": "True"})


from tb_forms import models


@api_view(http_method_names=["GET"])
def bydsss(request):
    if request.method == "GET":
        id = request.GET['record_id']
        path = '/mysite/files/ST/forms/pdf' + \
               eval(models.TbApplyform.objects.filter(wrecord_id=id)[0].file1)['href'].split('/')[-1]
        by_form_pdf(id, path)
        return response_origin({"status": "True"})
